<?php
namespace app\common\controller;

use com\Auth;
use think\Loader;
use think\Controller;
use think\Db;

/**
* 后台公用基础控制器
* @author taigu
* @version 2017-02-09
*/
class AdminBaseController extends Controller {
	
    protected function _initialize() {
        parent::_initialize();
        $this->checkAuth();
        $this->getMenu();
		$site_config = get_config('site_config');//配置
		config($site_config);//配置
    }
	//图片上传
    public function upload(){
    	include_once ('././vendor/aliyun-oss-php-sdk/autoload.php');
		$files = $_POST["value"];  
	    $tmp = base64_decode($files);
	    $fn = time()."_".rand(100000, 999999) . ".jpg";
		$fp = '././public/uploads/image/'. $fn;
		$fp1 = '././public/uploads/image/'. $fn;
	    $res=file_put_contents( $fp, $tmp);
		$ossClient = new \OSS\OssClient('LTAIaqGtJ3JDXJvv', 'Q2kTcyepAHX0VOR44OtszVoyOKE8gl', 'oss-cn-shanghai.aliyuncs.com');
		try{
			$res=$ossClient->uploadFile("long3",$fn,$fp1);
			$src='https://long3.oss-cn-shanghai.aliyuncs.com/'.$fn;
			unlink($fp1);
			return json(["code"=>200,'url'=>$src]);
		} catch(OssException $e) {
			return json(["code"=>404,'msg'=>'上传错误']);
		} 
	} 
	
	public function wang_upload(){
		include_once ('././vendor/aliyun-oss-php-sdk/autoload.php');
			foreach ($_FILES as $name => $file) {
				$info = getimagesize($file['tmp_name']);  
        		$ext = image_type_to_extension($info['2']);  
				$ossClient = new \OSS\OssClient('LTAIaqGtJ3JDXJvv', 'Q2kTcyepAHX0VOR44OtszVoyOKE8gl', 'oss-cn-shanghai.aliyuncs.com');
				$name=time()."_".rand(100000, 999999).$ext;
				try{
					$res=$ossClient->uploadFile("long3",$name,$file['tmp_name']);
					$result['code'] = 1;
					$result['msg'] = '上传成功！';
					$result['src']='http://long3.oss-cn-shanghai.aliyuncs.com/'.$name;
				}catch(OssException $e) {
					$result['code'] = 0;
					$result['msg'] = $file -> $e->getMessage();
				}
			}
		return json($result);
	}
    /**
     * 权限检查
     * @return bool
     */
    protected function checkAuth() {
		$admin_id = session('admin_id');
        if(!$admin_id){
            $this->redirect('admin/login/index');
        }
		$url = request()->module() . '/' . request()->controller() . '/' . request()->action();
        // 排除权限
        $not_check = ['admin/Index/index', 'admin/Index/welcome'];
		// 排除管理员ID
		$not_check_id = [1];
		if(!in_array($admin_id,$not_check_id) && !in_array($url,$not_check)){ 
          	$auth = new Auth();
            if (!$auth->check($url, $admin_id)){
            $this->error('没有权限');
            }
    	}
	}











    /**
     * 获取侧边栏菜单
     */
    protected function getMenu() {
        $menu     = [];
        $menu1     = [];
        $admin_id = session('admin_id');
        $id=Db::name('tg_auth_group_access')->where('uid',$admin_id)->field('group_id')->find();
		$role = Db::name('tg_auth_group')->field('rules')->where('id',$id['group_id'])->find();
		$array=explode(',',$role['rules']);
        $auth_rule_list = Db::name('tg_auth_rule')->order(['sort' => 'asc','add_time'=>'asc'])->where('status',1)->select();
        foreach ($auth_rule_list as $value) {
        	if($id['group_id']!=1){
         		if (in_array($value['id'], $array)) {
                		$menu[] = $value;
           	 	}
         	}else{
         		$menu[] = $value;
       	  	}
        }
        
        $menu = !empty($menu) ? array2tree($menu) : [];
        $this->assign('menu', $menu);
    }
    
    	/**
	 * 发送短信
	 * $mobile 手机号
	 * $template_no 模板编号(数据库主键)，注意不是模板ID
	 */
	protected function get_code($mobile, $template_no){
		// 获取短信模板
		$template = Db::name('sms_template') -> find($template_no);
		// 如果是验证码类型，则生成6位验证码
		$mun=rand(100000,999999);
		$msg = send_sms($mobile,$template['tid'],$template['sign_name'],$mun);		
		$data['mobile'] = $mobile;
		$data['code']=$mun;
		$data['add_time'] = now_time();
		if(isset($msg->result)) {
			$data['message'] = '发送成功';
			Db::name('sms_code')->insert($data);
			return toSuccess('发送成功');
		}else{
			$data['result'] = 0;
			$data['message'] = '发送失败:'.$msg->sub_msg;
			Db::name('sms_code')->insert($data);
			if($msg->sub_code == "isv.BUSINESS_LIMIT_CONTROL"){
				$err = "超过发送次数，请稍后再试";
				
			}else{
				$err = "发送失败";
				
			}
			return toError(408, $err);
		}
	}
    
}
